import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login.vue'
import { tip } from '@/tools/function'
import req from '@/http/req'
import url from '@/config/url'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/admin',
    component: () => import('@/views/admin/index.vue'),
    redirect: '/admin/dashboard',
    /*  组件内部路由 meta: { isLogin: true }, */
    children: [
      {
        path: 'goods',
        component: () => import('@/views/admin/Goods.vue'),
        /* 组件内部路由 meta: { isLogin: true } */
      },
      {
        path: 'user',
        component: () => import('@/views/admin/User.vue'),
        /* 组件内部路由meta: { isLogin: true } */
      },
      {
        path: 'dashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        /* 组件内部路由 meta: { isLogin: true } */
      }
    ]
    //路由独享守卫
    /* beforeEnter:(to,from,next) => {
      if(!localStorage.getItem('token')){
        tip('请先登录','error')
        next('/login')
      } else {
        req.get('http://127.0.0.1:5000/api/v1/profile').then((res) => {
          if (res.data.code === 401) {
            tip('请先登录','error')
            next('/login')
          }else{
            localStorage.setItem('userInfo',JSON.stringify(res.data.data))
          }
        })
      }
    }, */
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//每一个路由的全局守卫
router.beforeEach((to, from, next) => {
  if (to.meta.isLogin) {
    if (!localStorage.getItem('token')) {
      tip('请先登录', 'error')
      next('/login')
    } else {
      req.get(url.profile).then((res) => {
        if (res.data.code === 401) {
          tip('请先登录', 'error')
          next('/login')
        } else {
          localStorage.setItem('userInfo', JSON.stringify(res.data.data))
        }
      })
    }
  } else {
    next()
  }

})
export default router
